'use strict';

(function () {
    //Setup map events from a amap map object to trigger on a given element too,
    //then we just use ui-event to catch events from an element
    function bindMapEvents(scope, eventsStr, myObj, element) {
        angular.forEach(eventsStr.split(' '), function (eventName) {
            //Prefix all amap events with 'map-', so eg 'click'
            //for the amap doesn't interfere with a normal 'click' event
            var _eventName = eventName;
            if (_eventName == 'zoom_changed') {
                _eventName = 'zoomchange';
            }
            window.AMap.event.addListener(myObj, _eventName, function (event) {
                //触发使用ui-event绑定的事件
                element.triggerHandler('map-' + eventName, event);
                //We create an $apply if it isn't happening. we need better support for this
                //We don't want to use timeout because tons of these events fire at once,
                //and we only need one $apply
                if (!scope.$$phase) {
                    scope.$apply();
                }
            });
        });
    }

    app.value('uiMapConfig', {});
    app.directive('uiMap',
        ['uiMapConfig', '$parse', function (uiMapConfig, $parse) {

            var mapEvents = 'dragend zoomend click zoom_changed complete';
            var options = uiMapConfig || {};

            return {
                restrict: 'A',
                //doesn't work as E for unknown reason
                link: function (scope, elm, attrs) {
                    var opts = angular.extend({}, options, scope.$eval(attrs.uiOptions));
                    var map = new window.AMap.Map(elm[0], opts);
                    var model = $parse(attrs.uiMap);

                    //获取地图当前位置坐标
                    map.getCurrentMapPos_ = function () {
                        var pos = {};
                        var bounds = this.getBounds();   //获取可视区域
                        if (bounds == null) {
                            var center = this.map.getCenter();
                            if (center != null) {
                                pos = {
                                    "x1": center.lng,
                                    "y1": center.lat,
                                    "x2": center.lng,
                                    "y2": center.lat
                                }
                            }
                        } else {
                            var ne = bounds.getNorthEast(); //可视区域右上角
                            var sw = bounds.getSouthWest(); //可视区域左下角
                            pos = {
                                "x1": sw.lng,
                                "y1": sw.lat,
                                "x2": ne.lng,
                                "y2": ne.lat
                            }
                        }
                        return pos;
                    }
                    map.getMapCenter_ = function () {
                        var center = this.getCenter();
                        return {
                            "lng": center.lng,
                            "lat": center.lat,
                        }
                    }
                    //得到当前可视区域半径
                    map.getViewRadius_ = function () {
                        var center = this.getCenter();
                        var lnglat = new AMap.LngLat(center.lng, center.lat);
                        var bounds = this.getBounds();   //获取可视区域
                        var ne = bounds.getNorthEast(); //可视区域右上角
                        return lnglat.distance([ne.lng, ne.lat]);
                    }
                    //设置地图中心
                    map.setMapCenter_ = function (lat, lng) {
                        this.setCenter(new AMap.LngLat(lng, lat));
                    }
                    //设置控件
                    AMap.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.OverView', 'AMap.MapType', 'AMap.Autocomplete', 'AMap.PlaceSearch'], function () {
                        var autoOptions = {
                            city: "", //城市，默认全国
                            input: "input_id"//使用联想输入的input的id
                        };
                        var autocomplete = new AMap.Autocomplete(autoOptions);
                        AMap.event.addListener(autocomplete, "select", function (e) {
                            if (e.poi && e.poi.location) {
                                map.setZoom(15);
                                map.setCenter(e.poi.location);
                            }
                        });
                        map.addControl(new AMap.ToolBar());
                        map.addControl(new AMap.Scale());
                        // map.addControl(new AMap.OverView({isOpen:true}));
                        map.addControl(new AMap.MapType({defaultType: 0}));
                    })

                    /*   //搜索控件
                     AMap.plugin(['AMap.Autocomplete','AMap.PlaceSearch'],function(){
                     var autoOptions = {
                     city: "", //城市，默认全国
                     input: "input_id"//使用联想输入的input的id
                     };
                     var autocomplete= new AMap.Autocomplete(autoOptions);
                     AMap.event.addListener(autocomplete, "select", function(e){
                     if (e.poi && e.poi.location) {
                     map.setZoom(15);
                     map.setCenter(e.poi.location);
                     }
                     });
                     });*/
                    //添加区域范围
                    var lineArr = [
                        [114.479932, 30.490247],
                        [114.483494, 30.491468],
                        [114.486069, 30.492355],
                        [114.488186, 30.492899],
                        [114.492721, 30.493095],
                        [114.502935, 30.492825],
                        [114.507999, 30.492799],
                        [114.51332, 30.493934],
                        [114.518427, 30.495757],
                        [114.5298, 30.500158],
                        [114.533834, 30.490173],
                        [114.53407, 30.456315],
                        [114.504029, 30.447751],
                        [114.481241, 30.447825],
                        [114.481542, 30.484408],
                        [114.479932, 30.490247]
                    ];
                    var polyline = new AMap.Polyline({
                        path: lineArr,          //设置线覆盖物路径
                        strokeColor: "#0099ff", //线颜色
                        strokeOpacity: 0.9,       //线透明度
                        strokeWeight: 3,        //线宽
                        strokeStyle: "solid",   //线样式
                        strokeDasharray: [10, 5] //补充线样式
                    });
                    polyline.setMap(map);
                    /*  var  polygon = new AMap.Polygon({
                     path: polygonArr,//设置多边形边界路径
                     strokeColor: "#0099ff", //线颜色
                     strokeOpacity: 0.9, //线透明度
                     strokeWeight: 3,    //线宽
                     fillColor: "#f1ffea", //填充色
                     fillOpacity: 0//填充透明度
                     });
                     polygon.setMap(map);*/

                    map.newMapIcon_ = function (iconUrl, width, height) {
                        var size = new AMap.Size(width + 10, height + 10);
                        var icon = new AMap.Icon({
                            image: iconUrl,
                            //icon可缺省，缺省时为默认的蓝色水滴图标，
                            size: size,
                            imageSize: size
                        });
                        return icon;
                    }
                    map.newMapMarker_ = function (lat, lng, content, icon, draggable_, bemsObj_) {
                        var marker = new AMap.Marker({
                            icon: icon,
                            content: content,
                            position: [lat, lng],
                            draggable: draggable_,
                            map: this
                        });
                        marker.bemsObj = bemsObj_;
                        marker.getPosition_ = function () {
                            var pos = this.getPosition();
                            return {
                                lng: function () {
                                    return pos.lng;
                                },
                                lat: function () {
                                    return pos.lat;
                                }
                            }
                        }
                        return marker;
                    }

                    //销毁markers
                    map.removeMarkers_ = function (markers) {
                        map.remove(markers);
                    }
                    //创建巡航器
                    var pathSimplifierIns, navg1;

                    map.createNavigate_ = function (path, speed, img, width, height, rotateDegree) {

                        if (path.length === 0) {
                            return;
                        }
                        AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], function (PathSimplifier, $) {

                            if (!PathSimplifier.supportCanvas) {
                                alert('当前环境不支持 Canvas！');
                                return;
                            }

                            pathSimplifierIns = new PathSimplifier({
                                zIndex: 100,
                                //autoSetFitView:false,
                                map: map, //所属的地图实例

                                getPath: function (pathData, pathIndex) {

                                    return pathData.path;
                                },
                                getHoverTitle: function (pathData, pathIndex, pointIndex) {

                                    return null;
                                },
                                renderOptions: {

                                    renderAllPointsIfNumberBelow: -1 //绘制路线节点，如不需要可设置为-1
                                }
                            });

                            window.pathSimplifierIns = pathSimplifierIns;

                            //设置数据
                            pathSimplifierIns.setData([{
                                name: '轨迹',
                                path: path

                            }]);

                            //对第一条线路（即索引 0）创建一个巡航器
                            navg1 = pathSimplifierIns.createPathNavigator(0, {
                                loop: true, //循环播放
                                speed: speed,//巡航速度，单位千米/小时
                                pathNavigatorStyle: {
                                    autoRotate: true,
                                    width: width === undefined ? 64 : width,
                                    height: height === undefined ? 64 : height,
                                    initRotateDegree: rotateDegree,
                                    content: img === "upload/kache2.png" ? PathSimplifier.Render.Canvas.getImageContent(img, onload, onerror) : null,
                                    strokeStyle: null,
                                    fillStyle: null
                                    // lineHeight:64,
                                    // lineWidth:64
                                }
                            });

                            if (img !== "upload/kache2.png") {
                                var $markerContent = $("<div></div>");


                                $markerContent.html('<img src="' + img + '" style="width: 25px;height: 25px;border-radius: 400px;box-shadow: 0px 0px 7px 4px rgba(35, 183, 229, 0.8)">');

                                navg1.marker = new AMap.Marker({
                                    offset: new AMap.Pixel(-10, -20),
                                    content: $markerContent.get(0),
                                    map: map
                                });
                                navg1.on('move', function () {
                                    navg1.marker.setPosition(navg1.getPosition());
                                });
                            }
                            // navg1.marker.setPosition(navg1.getPosition());

                            /*navg1.onDestroy(function () {
                             navg1 = null;
                             navg1.marker.setMap(null);
                             $msg.html('');
                             });*/

                            navg1.start();
                        })
                    }

                    map.removeNavg1 = function () {
                        if (pathSimplifierIns != null) {
                            this.navg1 = null;
                            pathSimplifierIns.setData([]);
                            if (navg1.marker) {
                                navg1.marker.setMap(null);
                            }
                        }
                    }
                    //创建路径规划
                    // map.createDriving_ = function (data) {
                    /* AMap.service('AMap.Driving',function(){//回调函数
                     var driving = new AMap.Driving({
                     map: map,
                     city: '武汉市',
                     panel: "panel"
                     });
                     // 根据起终点经纬度规划驾车导航路线
                     // driving.search(new AMap.LngLat(114.49, 30.4602), new AMap.LngLat(114.50, 30.4808));
                     driving.search(new AMap.LngLat(114.49, 30.4602), new AMap.LngLat(114.50, 30.4808));
                     });
                     */


                    // }
                    //Set scope variable for the map
                    model.assign(scope, map);

                    bindMapEvents(scope, mapEvents, map, elm);
                }
            };


        }]);

    app.value('uiMapInfoWindowConfig', {isCustom: true});

    //Map Infor Window Controller
    app.controller('uiMapInfoWindowCtrl',
        ['$scope', '$element', '$attrs', '$exceptionHandler', 'uiMapInfoWindowConfig', '$parse', '$compile',
            function (scope, elm, attrs, $exceptionHandler, uiMapInfoWindowConfig, $parse, $compile) {
                var ctrl = this;

                var infoWindowEvents = 'closeclick content_change domready ' +
                    'position_changed zindex_changed';

                var options = {};//uiMapInfoWindowConfig || {};

                ctrl.init = function () {
                    var opts = angular.extend({
                        offset: new AMap.Pixel(8, -22),
                        isCustom: false
                    }, options, scope.$eval(attrs.uiOptions));
                    opts.content = elm[0];
                    var model = $parse(attrs.uiMapInfoWindow);
                    var infoWindow = model(scope);

                    if (!infoWindow) {
                        infoWindow = new window.AMap.InfoWindow(opts);
                        model.assign(scope, infoWindow);
                    }

                    bindMapEvents(scope, infoWindowEvents, infoWindow, elm);

                    /* The info window's contents dont' need to be on the dom anymore,
                     google maps has them stored.  So we just replace the infowindow element
                     with an empty div. (we don't just straight remove it from the dom because
                     straight removing things from the dom can mess up angular) */
                    elm.replaceWith('<div></div>');

                    //Decorate infoWindow.open to $compile contents before opening
                    var _open = infoWindow.open;
                    var _isInited = false;
                    infoWindow.open = function open(map, marker) {
                        if (!_isInited) {
                            $compile(elm.contents())(scope);
                            _isInited = true;
                        }
                        _open.call(infoWindow, map, marker.getPosition());
                    };
                }
            }]);

    //自定义Info Window Controller
    app.controller('CustomerInfoWindowCtrl',
        ['$scope', '$element', '$attrs', '$exceptionHandler', 'uiMapInfoWindowConfig', '$parse', '$compile', '$timeout', '$document',
            function (scope, elm, attrs, $exceptionHandler, uiMapInfoWindowConfig, $parse, $compile, $timeout, $document) {
                var ctrl = this;

                var infoWindowEvents = 'closeclick content_change domready ' +
                    'position_changed zindex_changed';

                var options = uiMapInfoWindowConfig || {};

                ctrl.init = function () {
                    var opts = angular.extend({}, options, scope.$eval(attrs.uiOptions));
                    var model = $parse(attrs.uiMapInfoWindowCus);
                    var infoWindow = model(scope);

                    if (!infoWindow) {
                        infoWindow = {};
                        model.assign(scope, infoWindow);
                    }

                    var _isInited = false;
                    infoWindow.open = function (a1, a2, a3, a4, a5, a6) {
                        if (!_isInited) {
                            _isInited = true;
                        }
                        $timeout(function () {
                            elm.triggerHandler('dialog-open');
                            elm.show();
                        }, 100)
                    };
                    infoWindow.close = function () {
                        elm.hide(100);
                    }
                    //设置绝对定位并隐藏最下方的箭头
                    elm.css({position: 'absolute', display: 'none', 'zIndex': 1026}).find('.arrow-bottom').hide();
                }
            }]);

    app.directive('uiMapInfoWindow',
        ['uiMapInfoWindowConfig', '$parse', '$compile', function (uiMapInfoWindowConfig, $parse, $compile) {
            return {
                controller: 'uiMapInfoWindowCtrl',
                link: function (scope, elm, attrs, ctrls) {
                    ctrls.init();
                }
            };
        }]);

    app.directive('uiMapInfoWindowCus',
        ['$parse', '$compile', function ($parse, $compile) {
            return {
                controller: 'CustomerInfoWindowCtrl',
                link: function (scope, elm, attrs, ctrls) {
                    ctrls.init();
                }
            };
        }]);

    /*
     * Map overlay directives all work the same. Take map marker for example
     * <ui-map-marker="myMarker"> will $watch 'myMarker' and each time it changes,
     * it will hook up myMarker's events to the directive dom element.  Then
     * ui-event will be able to catch all of myMarker's events. Super simple.
     */
    function mapOverlayDirective(directiveName, events) {
        app.directive(directiveName, [function () {
            return {
                restrict: 'A',
                link: function (scope, elm, attrs) {
                    scope.$watch(attrs[directiveName], function (newObject) {
                        if (newObject) {
                            bindMapEvents(scope, events, newObject, elm);
                        }
                    });
                }
            };
        }]);
    }

    mapOverlayDirective('uiMapMarker',
        'click dragstart dragend mouseover mouseout');

})();